/**
 * Created by jiachenpan on 16/11/18.
 */
/* 日期或中国标准时间转毫秒数  时间戳*1000就是毫秒数*/
export function dateToMs(date) {
	let result = new Date(date).getTime()
	return result
}
/**毫秒数或中国标准时间转日期 */
export function msToDate(msec) {
	let datetime = new Date(msec)
	let year = datetime.getFullYear()
	let month = datetime.getMonth()
	let date = datetime.getDate()
	let hour = datetime.getHours()
	let minute = datetime.getMinutes()
	let second = datetime.getSeconds()

	let result1 =
		year +
		'-' +
		(month + 1 >= 10 ? month + 1 : '0' + (month + 1)) +
		'-' +
		(date + 1 < 10 ? '0' + date : date) +
		' ' +
		(hour + 1 < 10 ? '0' + hour : hour) +
		':' +
		(minute + 1 < 10 ? '0' + minute : minute) +
		':' +
		(second + 1 < 10 ? '0' + second : second)

	let result2 =
		year +
		'-' +
		(month + 1 >= 10 ? month + 1 : '0' + (month + 1)) +
		'-' +
		(date + 1 < 10 ? '0' + date : date)
	let result3 =
		year +
		'年' +
		(month + 1 >= 10 ? month + 1 : '0' + (month + 1)) +
		'月' +
		(date + 1 < 10 ? '0' + date : date) +
		' ' +
		(hour + 1 < 10 ? '0' + hour : hour) +
		':' +
		(minute + 1 < 10 ? '0' + minute : minute)
	let result = {
		hasTime: result1,
		withoutTime: result2,
		cTime: result3
	}

	return result
}

// 花费时间(以小时记)[向上取分钟整数]
export function timeSpent(num) {
	let aa = 0
	if (num >= 60 && num < 60 * 24) {
		aa = Math.floor(num / 60) + '小时' + Math.ceil(num % 60) + '分钟'
	} else if (num >= 60 * 24) {
		let myDay = Math.floor(num / 60 / 24)
		let myHour = Math.floor((num - myDay * 60 * 24) / 60)
		let myMinute = (num - myDay * 60 * 24) % 60
		aa = myDay + '天' + myHour + '小时' + Math.ceil(myMinute) + '分钟'
	} else {
		aa = Math.ceil(num) + '分钟'
	}

	return aa
}

export function parseTime(time, cFormat) {
	if (arguments.length === 0) {
		return null
	}
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
			time = parseInt(time)
		}
		if (typeof time === 'number' && time.toString().length === 10) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}

export function formatTime(time1) {
	let time = new Date(time1)
	let timestamp = time.getTime()
	let nowstamp = Date.now()
	let differ = nowstamp - timestamp
	if (differ < 0) {
		return ''
	}
	if (differ < 3600000) {
		//时间小于1小时
		let min = parseInt(differ / 60000)
		return `${min}分钟前`
	} else if (differ < 86400000 && differ > 3600000) {
		//时间小于一天
		let hour = parseInt(differ / 3600000)
		return `${hour}小时前`
	} else if (differ < 604800000 && differ > 86400000) {
		//时间小于7天
		let day = parseInt(differ / 86400000)
		return `${day}天前`
	} else if (differ < 31536000000 && differ > 604800000) {
		//时间小于1年
		let month = time.getMonth()
		let d = time.getDate()
		month += 1
		return `${month}-${d}`
	} else if (differ > 31536000000) {
		//时间大于1年
		let year = parseInt(differ / 604800000)
		return `${year}年前`
	}
}

export function compFilter(value, fmt) {
	let getDate = new Date(value)
	let o = {
		'M+': getDate.getMonth() + 1,
		'd+': getDate.getDate(),
		'h+': getDate.getHours(),
		'm+': getDate.getMinutes(),
		's+': getDate.getSeconds(),
		'q+': Math.floor((getDate.getMonth() + 3) / 3),
		S: getDate.getMilliseconds()
	}
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length))
	}
	for (let k in o) {
		if (new RegExp('(' + k + ')').test(fmt)) {
			fmt = fmt.replace(
				RegExp.$1,
				RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
			)
		}
	}
	console.log(fmt)
	return fmt
}

// 格式化时间
export function getQueryObject(url) {
	url = url == null ? window.location.href : url
	const search = url.substring(url.lastIndexOf('?') + 1)
	const obj = {}
	const reg = /([^?&=]+)=([^?&=]*)/g
	search.replace(reg, (rs, $1, $2) => {
		const name = decodeURIComponent($1)
		let val = decodeURIComponent($2)
		val = String(val)
		obj[name] = val
		return rs
	})
	return obj
}

// 空值、undefined、 null值校验
export function isEmpty(value) {
	if (typeof value == 'undefined' || value == null) {
		return true
	} else {
		let trimData = Trim(value)
		if (trimData == '') {
			return true
		} else {
			return false
		}
	}
}

function Trim(str) {
	return str.replace(/(^\s*)|(\s*$)/g, '')
}
/**
 *get getByteLen
 * @param {Sting} val input value
 * @returns {number} output value
 */
export function getByteLen(val) {
	let len = 0
	for (let i = 0; i < val.length; i++) {
		if (val[i].match(/[^\x00-\xff]/gi) != null) {
			len += 1
		} else {
			len += 0.5
		}
	}
	return Math.floor(len)
}

export function cleanArray(actual) {
	const newArray = []
	for (let i = 0; i < actual.length; i++) {
		if (actual[i]) {
			newArray.push(actual[i])
		}
	}
	return newArray
}

export function param(json) {
	if (!json) return ''
	return cleanArray(
		Object.keys(json).map(key => {
			if (json[key] === undefined) return ''
			return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
		})
	).join('&')
}

export function param2Obj(url) {
	const search = url.split('?')[1]
	if (!search) {
		return {}
	}
	return JSON.parse(
		'{"' +
		decodeURIComponent(search)
		.replace(/"/g, '\\"')
		.replace(/&/g, '","')
		.replace(/=/g, '":"') +
		'"}'
	)
}

export function html2Text(val) {
	const div = document.createElement('div')
	div.innerHTML = val
	return div.textContent || div.innerText
}

export function objectMerge(target, source) {
	/* Merges two  objects,
	     giving the last one precedence */

	if (typeof target !== 'object') {
		target = {}
	}
	if (Array.isArray(source)) {
		return source.slice()
	}
	Object.keys(source).forEach(property => {
		const sourceProperty = source[property]
		if (typeof sourceProperty === 'object') {
			target[property] = objectMerge(target[property], sourceProperty)
		} else {
			target[property] = sourceProperty
		}
	})
	return target
}

export function toggleClass(element, className) {
	if (!element || !className) {
		return
	}
	let classString = element.className
	const nameIndex = classString.indexOf(className)
	if (nameIndex === -1) {
		classString += '' + className
	} else {
		classString =
			classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length)
	}
	element.className = classString
}

export const pickerOptions = [{
		text: '今天',
		onClick(picker) {
			const end = new Date()
			const start = new Date(new Date().toDateString())
			end.setTime(start.getTime())
			picker.$emit('pick', [start, end])
		}
	},
	{
		text: '最近一周',
		onClick(picker) {
			const end = new Date(new Date().toDateString())
			const start = new Date()
			start.setTime(end.getTime() - 3600 * 1000 * 24 * 7)
			picker.$emit('pick', [start, end])
		}
	},
	{
		text: '最近一个月',
		onClick(picker) {
			const end = new Date(new Date().toDateString())
			const start = new Date()
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
			picker.$emit('pick', [start, end])
		}
	},
	{
		text: '最近三个月',
		onClick(picker) {
			const end = new Date(new Date().toDateString())
			const start = new Date()
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
			picker.$emit('pick', [start, end])
		}
	}
]

export function getTime(type) {
	if (type === 'start') {
		return new Date().getTime() - 3600 * 1000 * 24 * 90
	} else {
		return new Date(new Date().toDateString())
	}
}

export function debounce(func, wait, immediate) {
	let timeout, args, context, timestamp, result

	const later = function() {
		// 据上一次触发时间间隔
		const last = +new Date() - timestamp

		// 上次被包装函数被调用时间间隔last小于设定时间间隔wait
		if (last < wait && last > 0) {
			timeout = setTimeout(later, wait - last)
		} else {
			timeout = null
			// 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
			if (!immediate) {
				result = func.apply(context, args)
				if (!timeout) context = args = null
			}
		}
	}

	return function(...args) {
		context = this
		timestamp = +new Date()
		const callNow = immediate && !timeout
		// 如果延时不存在，重新设定延时
		if (!timeout) timeout = setTimeout(later, wait)
		if (callNow) {
			result = func.apply(context, args)
			context = args = null
		}

		return result
	}
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 */
export function deepClone(source) {
	if (!source && typeof source !== 'object') {
		throw new Error('error arguments, shallowClone')
	}
	const targetObj = source.constructor === Array ? [] : {}
	Object.keys(source).forEach(keys => {
		if (source[keys] && typeof source[keys] === 'object') {
			targetObj[keys] = deepClone(source[keys])
		} else {
			targetObj[keys] = source[keys]
		}
	})
	return targetObj
}

export function uniqueArr(arr) {
	return Array.from(new Set(arr))
}

export function isExternal(path) {
	return /^(https?:|mailto:|tel:)/.test(path)
}

/**
 * 截取完整URL的文件名
 * @export
 * @param {*} path
 * @returns
 */
export function getUrlFileName(path) {
	try {
		let fileName = path.split('/')
		return decodeURIComponent(fileName[fileName.length - 1])
	} catch (err) {}
}
/**
 * 不规则数组重组
 * @export
 * @param {*} arr
 * @returns
 */
export async function mapArray(arr) {
	let newarr = await arr.map(x => {
		return x.url
	})
	return await newarr.join(',')
}
/**
 * 是否是IE判定
 * @export
 * @param {*} Boolean
 * @returns
 */
export async function isIE() {
	let ms_ie = false
	let ua = window.navigator.userAgent
	let old_ie = ua.indexOf('MSIE ')
	let new_ie = ua.indexOf('Trident/')

	if (old_ie > -1 || new_ie > -1) {
		ms_ie = true
	}

	if (ms_ie) {
		document.documentElement.className += ' ie'
	}
	return ms_ie
}

/**
 * @desc build a get request(构建一个带hash值的get请求)
 * @param
 */
export function buildGET(basePort, json) {
	let buildGet = basePort
	let fistNumber = 0
	for (var key in json) {
		let littlePort = ''
		if (json[key] != null && json[key] != 'null') {
			if (fistNumber == 0) {
				littlePort = '?' + key + '=' + json[key]
				fistNumber++
			} else {
				littlePort = '&' + key + '=' + json[key]
			}
			buildGet += littlePort
		}
	}
	return String(buildGet)
}

/**
 * 模拟window.open()
 * @export
 * @param {url}
 * @returns
 */
export function winOpen(url) {
	let a = document.createElement('a')
	a.setAttribute('href', url)
	a.setAttribute('target', '_blank')
	document.body.appendChild(a)
	a.click()
	document.body.removeChild(a)
}

/**
 * 内联下载
 * @export
 * @param {url}
 * @returns
 */
export function downloadOpen(url) {
	let ifr = document.createElement('iframe')
	ifr.src = url
	ifr.style.display = 'none'
	ifr.onload = function() {
		document.body.removeChild(ifr)
	}
	document.body.appendChild(ifr)
}

/**
 * url search参数拼接
 * @export
 * @param {url}
 * @returns
 */

export function urlArgs() {
	var args = {}
	var query = location.search.substring(1)
	var pairs = query.split('&')
	for (var i = 0; i < pairs.length; i++) {
		var pos = pairs[i].indexOf('=')
		if (pos == -1) continue
		var name = pairs[i].substring(0, pos)
		var value = pairs[i].substring(pos + 1)
		value = decodeURIComponent(value)
		args[name] = value
	}
	return args
}
// 获取url的参数
export const queryString = () => {
	let _queryString = {}
	const _query = window.location.search.substr(1)
	const _vars = _query.split('&')
	_vars.forEach((v, i) => {
		const _pair = v.split('=')
		if (!_queryString.hasOwnProperty(_pair[0])) {
			_queryString[_pair[0]] = decodeURIComponent(_pair[1])
		} else if (typeof _queryString[_pair[0]] === 'string') {
			const _arr = [_queryString[_pair[0]], decodeURIComponent(_pair[1])]
			_queryString[_pair[0]] = _arr
		} else {
			_queryString[_pair[0]].push(decodeURIComponent(_pair[1]))
		}
	})
	return _queryString
}
/* 
  合并参数
*/
async function args2Url(ujson) {
	var arr = [],
		str
	for (var obj in ujson) {
		await arr.push(`${obj}=${ujson[obj]}`)
	}
	str = await arr.join('&')
	return str
}
export async function fixUrl() {
	let ujson = await urlArgs()
	ujson['sto'] = 'weixin2share'
	ujson['sf'] = 'edudingdangcode'
	let str = await args2Url(ujson)
	let _url = `${window.location.protocol}//${window.location.host}${window.location.pathname}?${str}`
	return _url
}

// 模拟点击

export const clickButton = id => {
	let el = document.getElementById(id)
	if (/msie/i.test(navigator.userAgent)) {
		//IE
		el.fireEvent('onclick')
	} else {
		var e = document.createEvent('MouseEvent')
		e.initEvent('click', false, false)
		el.dispatchEvent(e)
	}
}

export function generateUUID() {
	var d = new Date().getTime()
	if (window.performance && typeof window.performance.now === 'function') {
		d += performance.now() //use high-precision timer if available
	}
	var uuid = 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		var r = (d + Math.random() * 16) % 16 | 0
		d = Math.floor(d / 16)
		return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
	})
	return uuid
}

export const createScript = (src, id, cb) => {
	let scriptDom = document.createElement('script')
	scriptDom.src = src
	scriptDom.id = id
	scriptDom.async = true
	let head = document.getElementsByTagName('body')[0]
	head.appendChild(scriptDom)
	scriptDom.onload = scriptDom.onreadystatechange = function() {
		if (
			!scriptDom.readyState || //这是FF的判断语句，因为ff下没有readyState这个值，IE的readyState肯定有值
			scriptDom.readyState === 'loaded' ||
			scriptDom.readyState === 'complete' // 这是IE的判断语句
		) {
			cb && cb()
		}
	}
}

export const SkLoad = () => {
	// 获取Sk集合是否加载
	let isSk = window.Sk
	if (!isSk) {
		// 组件加载，引入全局Sk
		createScript(process.env.PUBLIC_URL + '/skulpt.min.js', 'sku', () => {
			createScript(process.env.PUBLIC_URL + '/skulpt-stdlib.js', 'sku2', () => {
				setTimeout(() => {
					return true
				}, 300)
			})
		})
	}
}
